<?php

// ------------------------------------------------------------------------
// |@Author       : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2025-05-04 23:35:19
// |@----------------------------------------------------------------------
// |@LastEditTime : 2025-05-11 10:02:40
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Description  :
// |@----------------------------------------------------------------------
// |@FilePath     : CacheTrait.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2025 http://www.ladmin.cn All Rights Reserved.
// ------------------------------------------------------------------------
declare (strict_types=1);

namespace think\admin\traits;

/**
 * 缓存特性
 * 用于 Repository 层实现数据缓存
 */
trait CacheTrait
{
    /**
     * 缓存过期时间（秒）
     * @var int
     */
    protected int $cacheExpire = 3600;

    /**
     * 获取缓存键名
     * @param string $key
     * @return string
     */
    protected function getCacheKey(string $key): string
    {
        return $key;
    }

    /**
     * 设置缓存
     * @param string $key
     * @param mixed $value
     * @param int|null $expire
     * @return bool
     */
    protected function setCache(string $key, mixed $value, ?int $expire = null): bool
    {
        return $this->app->cache->set(
            $this->getCacheKey($key),
            $value,
            $expire ?? $this->cacheExpire
        );
    }

    /**
     * 获取缓存
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    protected function getCache(string $key, mixed $default = null): mixed
    {
        return $this->app->cache->get($this->getCacheKey($key), $default);
    }

    /**
     * 删除缓存
     * @param string $key
     * @return bool
     */
    protected function deleteCache(string $key): bool
    {
        return $this->app->cache->delete($this->getCacheKey($key));
    }

    /**
     * 清除缓存
     * @param array $keys
     * @return bool
     */
    protected function clearCache(array $keys = []): bool
    {
        if (empty($keys)) {
            return $this->app->cache->tag($this->cachePrefix)->clear();
        }

        foreach ($keys as $key) {
            $this->deleteCache($key);
        }
        return true;
    }

    /**
     * 缓存查询结果
     * @param string $key
     * @param callable $callback
     * @param int|null $expire
     * @return mixed
     */
    protected function remember(string $key, callable $callback, ?int $expire = null): mixed
    {
        return $this->app->cache->remember($this->getCacheKey($key), $callback, $expire ?? $this->cacheExpire);
    }
}
